import aiohttp
from mg_app_framework import MesCode, get_context, get_logger, set_context
from common.decorator import time_costs


def set_aiohttp_session():
    aio_http_session = aiohttp.ClientSession()
    set_context("aio_http_session", aio_http_session)


def get_aiohttp_session() -> aiohttp.ClientSession:
    aio_http_session = get_context("aio_http_session")
    return aio_http_session


@time_costs
async def send_http_request(method, url, data=None, headers=None):
    """
    异步HTTP请求调用
    :param method: HTTP方法，如 'GET' 或 'POST'
    :param url: 请求的URL
    :param data: 请求的数据
    :param headers: 请求的头部信息
    :return: 包含响应信息的字典
    """
    session = get_aiohttp_session()
    try:
        async with session.request(method, url, data=data, headers=headers) as response:
            response_data = await response.json()
            res = {
                "code": response.status,
                "data": response_data,
                "info": response.reason,
            }
            get_logger().info(
                f"send_http_request suc, url: {url}, params: {data}, response: {res}"
            )
    except Exception as e:
        # 接口调用报错，服务器内的错误
        res = {"code": MesCode.fail, "data": {}, "info": "服务器调用异常"}
        get_logger().error(f"send_http_request fail, url: {url}, params: {data}, error: {e}")

    return res


async def send_http_get_request(url, get_data=None, headers=None):
    """
    异步GET请求调用
    :param url: 请求的URL
    :param get_data: GET请求的参数
    :param headers: 请求的头部信息
    :return: 包含响应信息的字典
    """
    return await send_http_request("GET", url, data=get_data, headers=headers)


async def send_http_post_request(url, post_data=None, headers=None):
    """
    异步POST请求调用
    :param url: 请求的URL
    :param post_data: POST请求的数据
    :param headers: 请求的头部信息
    :return: 包含响应信息的字典
    """
    return await send_http_request("POST", url, data=post_data, headers=headers)
